package com.example.server.security;

import com.example.server.exception.YebException;
import com.example.server.mapper.MenuMapper;
import com.example.server.pojo.Admin;
import com.example.server.pojo.Menu;
import com.example.server.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author CuiQingFeng
 */
@Component
public class DefaultSessionBasedAuthorizeInterceptor implements HandlerInterceptor {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        /*
           获取当前请求有哪些角色可以访问

           获取当前用户有哪些角色

           比较两者角色是否有交集
         */
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        // 加载所有的menu列表，每个menu都会携带一个role列表
            // TODO 加载menu信息可以使用缓存来做
        List<Menu> menus = menuMapper.findAllWithRoles();

        // 使用requestUri地址匹配查到的menu列表

        List<Role> allowedRoles = null;
        for (Menu menu : menus) {

            if (antPathMatcher.match(menu.getUrl(), requestURI)) {

                allowedRoles = menu.getRoles();
            }
        }

        if (allowedRoles == null || allowedRoles.size() == 0) {
            return true;
        }

        // 如此就可以获取到当前请求的roles

        Admin admin = (Admin) request.getSession().getAttribute("auth");

        for (Role allowedRole : allowedRoles) {

            for (Role role : admin.getRoles()) {

                if (role.equals(allowedRole)) {
                    return true;
                }
            }
        }

        // 41x
        throw new YebException(411, "当前用户不具备该权限，无法访问！");

    }
}
